package com.swj.modules.system.controller;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.swj.common.core.constant.UserConstants;
import com.swj.common.core.model.SysDept;
import com.swj.common.core.model.SysRole;
import com.swj.common.core.model.SysUser;
import com.swj.common.core.model.vo.LoginUserVo;
import com.swj.common.core.model.vo.TreeSelect;
import com.swj.common.core.model.web.RestResult;
import com.swj.common.core.utils.ResponseUtil;
import com.swj.common.core.utils.SysStringUtil;
import com.swj.common.core.utils.poi.ExcelUtil;
import com.swj.common.log.annotation.Log;
import com.swj.common.log.enums.BusinessType;
import com.swj.common.security.annotation.RequiresPermissions;
import com.swj.common.security.utils.SecurityUtil;
import com.swj.modules.system.model.SysUserQueryVO;
import com.swj.modules.system.service.*;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/user")
public class SysUserController {
    @Resource
    private ISysUserService userService;

    @Resource
    private ISysPermissionService permissionService;

    @Resource
    private ISysConfigService configService;

    @Resource
    private ISysDeptService deptService;

    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysPostService postService;


    /**
     * 获取当前用户信息
     * 用于认证模块远程rpc调用
     *
     * @param userName 用户姓名
     * @return loginUserVo 登录用户前端对象,包含角色集合,权限集合
     */
    @GetMapping("/info/{userName}")
    public RestResult<?> info(@PathVariable("userName") String userName) {
        SysUser user = userService.selectUserAndRolesAndPermissonsByName(userName);
        if (ObjectUtils.isNull(user)) {
            return ResponseUtil.fail("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setSysUser(user);
        loginUserVo.setUserId(user.getId());
        loginUserVo.setLoginTime(LocalDateTime.now());
        loginUserVo.setRoles(roles);
        loginUserVo.setPermissions(permissions);
        return ResponseUtil.successWithObj(loginUserVo);
    }

    /**
     * 修改用户表里的登录信息相关字段
     * 用于认证模块远程rpc调用
     */
    @PutMapping("/recordLogin")
    public RestResult<?> record(@Validated @RequestBody SysUser user) {
        userService.updateById(user);
        return ResponseUtil.success("记录成功");
    }

    /**
     * 分页获取用户列表
     */
    @RequiresPermissions("sys:user:list")
    @GetMapping("/page")
    public RestResult<Page<SysUser>> page(SysUserQueryVO user) {
        Page<SysUser> list = userService.selectUserPage(user);
        return ResponseUtil.successWithPageList(list);
    }

    /**
     * 获取用户列表(不分页)
     */
    @RequiresPermissions("sys:user:list")
    @GetMapping("/list")
    public RestResult<List<SysUser>> list() {
        List<SysUser> list = userService.selectUserList(null);
        return ResponseUtil.successWithList(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUserQueryVO user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    public RestResult<?> importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtil.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return ResponseUtil.success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 注册用户信息
     */
    @PostMapping("/register")
    public RestResult<?> register(@RequestBody SysUser sysUser) {
        String userName = sysUser.getUserName();
        if ("false".equals(configService.selectConfigByKey("sys.account.registerUser"))) {
            return ResponseUtil.fail("当前系统没有开启注册功能！");
        }
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(sysUser))) {
            return ResponseUtil.fail("保存用户'" + userName + "'失败，注册账号已存在");
        }
        return ResponseUtil.successWithObj(userService.registerUser(sysUser));
    }

    /**
     * 获取用信息权限信息
     * 包含角色集合,权限集合
     * 主要用于前端路由守卫
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public RestResult<Map<String, Object>> getInfo() {
        SysUser user = userService.selectUserById(SecurityUtil.getUserId());
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        Map<String, Object> infoMap = new HashMap<>();
        infoMap.put("user", user);
        infoMap.put("roles", roles);
        infoMap.put("permissions", permissions);
        return ResponseUtil.successWithObjAndMsg(infoMap, "查询成功");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @RequiresPermissions("system:user:info")
    @GetMapping(value = {"/", "/{userId}"})
    public RestResult<Map<String, Object>> getInfo(@PathVariable(value = "userId", required = false) String userId) {
        userService.checkUserDataScope(userId);
        List<SysRole> roles = roleService.selectRoleAll();
        Map<String, Object> info = new HashMap<>(5);
        info.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        info.put("posts", postService.selectPostAll());
        if (SysStringUtil.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            info.put("user", sysUser);
            info.put("postIds", postService.selectPostListByUserId(userId));
            info.put("roleIds", sysUser.getRoles().stream().map(SysRole::getId).collect(Collectors.toList()));
        }
        return ResponseUtil.successWithObjAndMsg(info, "查询成功");
    }

    /**
     * 新增用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public RestResult<?> add(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) {
            return ResponseUtil.failWithError("新增用户失败", "新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (SysStringUtil.isNotEmpty(user.getPhoneNumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return ResponseUtil.failWithError("新增用户失败", "新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (SysStringUtil.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return ResponseUtil.failWithError("新增用户失败", "新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtil.getUsername());
        user.setPassword(SecurityUtil.encryptPassword(user.getPassword()));
        userService.insertUser(user);
        return ResponseUtil.success("添加成功");
    }


    /**
     * 修改用户
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public RestResult<?> edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getId());
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) {
            return ResponseUtil.failWithError("修改失败", "修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (SysStringUtil.isNotEmpty(user.getPhoneNumber()) && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return ResponseUtil.failWithError("修改失败", "修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (SysStringUtil.isNotEmpty(user.getEmail()) && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return ResponseUtil.failWithError("修改失败", "修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtil.getUsername());
        return ResponseUtil.successWithObj(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @RequiresPermissions("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public RestResult<?> remove(@PathVariable String[] userIds) {
        if (ArrayUtils.contains(userIds, SecurityUtil.getUserId())) {
            return ResponseUtil.failWithError("删除失败", "当前用户不能删除");
        }
        userService.deleteUserByIds(userIds);
        return ResponseUtil.success("删除成功");
    }

    /**
     * 状态切换
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public RestResult<?> changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getId());
        if (userService.updateById(user)) {
            return ResponseUtil.success("切换状态成功");
        }
        return ResponseUtil.fail("切换状态失败");
    }

    /**
     * 重置密码
     */
    @RequiresPermissions("sys:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public RestResult<?> resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getId());
        user.setPassword(SecurityUtil.encryptPassword(user.getPassword()));
        if (userService.updateById(user)) {
            return ResponseUtil.success("修改成功");
        }
        return ResponseUtil.fail("重置密码失败");
    }


    /**
     * 根据用户编号获取授权角色
     */
    @RequiresPermissions("system:user:query")
    @GetMapping("/authRole/{userId}")
    public RestResult<Map<String, Object>> authRole(@PathVariable("userId") String userId) {
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        Map<String, Object> info = new HashMap<>(5);
        info.put("user", user);
        info.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ResponseUtil.successWithObj(info);
    }

    /**
     * 用户授权角色
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public RestResult insertAuthRole(String userId, String roleIds) {
        userService.checkUserDataScope(userId);
        SysUser user = new SysUser();
        user.setId(userId);
        user.setRoleIds(roleIds.split(","));
        // 删除用户与角色关联
        roleService.deleteUserRoleRelation(user);
        // 新增用户与角色管理
        roleService.insertUserRoleRelation(user);
        return ResponseUtil.successPut("修改成功");
    }

    /**
     * 获取部门树列表
     */
    @RequiresPermissions("system:user:list")
    @GetMapping("/deptTree")
    public RestResult<List<TreeSelect>> deptTree(SysDept dept) {
        return ResponseUtil.successWithListAndMsg(deptService.selectDeptTreeList(dept), "查询成功");
    }
}
